package context.support;

import beans.factorys.support.DefaultBeanFactory;
import beans.factorys.xml.XmlBeanDefinitionReader;
import context.ApplicationContext;
import core.io.Resource;
import utils.ClassUtils;

/**
 * Created by ZhaiGuaili on 2018/7/9.
 */
public abstract class AbstractApplicationContext implements ApplicationContext {
    private DefaultBeanFactory factory;

    private ClassLoader classLoader;


    public AbstractApplicationContext(String configFile){
        this.factory = new DefaultBeanFactory();
        Resource resource = getResourceByPath(configFile);
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinition(resource);
        this.factory.setBeanClassLoader(this.getBeanClassLoader());


    }

    public Object getBean(String beanId)throws Exception{
        return this.factory.getBean(beanId);
    }

    protected abstract Resource getResourceByPath(String configFile);



    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public ClassLoader getBeanClassLoader() {
        return (this.classLoader != null? classLoader:ClassUtils.getDefaultClassLoader());
    }

}
